package com.sky.controller.admin;


import com.sky.dto.FlyPageQueryDTO;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.FlyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * 无人机管理
 */
@RestController
@RequestMapping("/admin/fly")
@Slf4j
@Api(tags = "无人机相关接口")
public class FlyController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private FlyService flyService;

    /**
     * 无人机分页查询
     * @param flyPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页查询无人机")
    public Result<PageResult> page(FlyPageQueryDTO flyPageQueryDTO){
        log.info("分页查询无人机：{}", flyPageQueryDTO);
        PageResult pageResult = flyService.pageQuery(flyPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 更改无人机信息
     * @param flyPageQueryDTO
     * @return
     */
    @PutMapping
    @ApiOperation("更改无人机信息")
    public Result update(@RequestBody FlyPageQueryDTO flyPageQueryDTO){
        log.info("更改无人机信息：{}", flyPageQueryDTO);
        flyService.update(flyPageQueryDTO);
        // 清理缓存数据
        clearCache("fly:*");
        return Result.success();
    }

    /**
     * 添加无人机
     * @param flyPageQueryDTO
     * @return
     */
    @PostMapping
    @ApiOperation("添加无人机")
    public Result save(@RequestBody FlyPageQueryDTO flyPageQueryDTO){
        log.info("添加无人机：{}", flyPageQueryDTO);
        flyService.save(flyPageQueryDTO);
        //清理缓存数据
        clearCache("fly:*");
        return Result.success();
    }

    //删除无人机
    @DeleteMapping
    @ApiOperation("删除无人机")
    public Result delete(@RequestParam Long id){
        log.info("删除无人机：{}", id);
        flyService.delete(id);
        //清理缓存数据
        clearCache("fly:*");
        return Result.success();
    }


    /**
     * 清理缓存数据
     * @param pattern
     */
    private void clearCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
